package service

import (
	"context"
	"fmt"
	"regexp"
	"time"

	pb "customer/api/customer"
	verifyCode "customer/api/verifyCode"
	"customer/internal/data"

	"github.com/go-kratos/kratos/v2/transport/grpc"
)

type CustomerService struct {
	pb.UnimplementedCustomerServer
	customerData *data.CustomerData // 更新CustomerService的定义，与CustomerData建立联系
}

// 更新CustomerService的定义，与CustomerData建立联系
func NewCustomerService(cd *data.CustomerData) *CustomerService {
	return &CustomerService{
		customerData: cd,
	}
}

func (s *CustomerService) GetVerifyCode(ctx context.Context, req *pb.GetVerifyCodeRequest) (*pb.GetVerifyCodeReply, error) {
	//正则校验手机号码
	param := `^1[3-9]\d{9}$`
	regexpParam := regexp.MustCompile(param)
	if !regexpParam.MatchString(req.Telephone) {
		return &pb.GetVerifyCodeReply{
			Code:    1,
			Message: "手机号码格式不正确",
		}, nil
	}

	// 二 通过验证码服务生成验证码 （服务间的调用，GRPC）
	conn, err := grpc.DialInsecure(
		context.Background(),
		grpc.WithEndpoint("localhost:9100"), // verifyCode 服务端地址;临时写死 根据具体填写
	)

	if err != nil {
		return &pb.GetVerifyCodeReply{
			Code:    1,
			Message: "验证码调用失败",
		}, nil
	}

	// 关闭链接
	defer func() {
		_ = conn.Close()
	}()

	// 2.2 发送获取验证码的请求
	client := verifyCode.NewVerifyCodeClient(conn)
	code, _ := client.GetVerifyCode(context.Background(), &verifyCode.GetVerifyCodeRequest{
		Length: 6,
		Type:   verifyCode.TYPE_DIGIT,
	})

	const lift = 60
	// 设置验证码
	fmt.Println("code:", code.Code)
	err = s.customerData.SetVerifyCode(req.Telephone, code.Code, lift)
	if err != nil {
		return &pb.GetVerifyCodeReply{
			Code:    1,
			Message: "验证码调用失败",
		}, nil
	}
	/*
		// 使用redis临时存储
		// 链接redis
		//redis.ParseURL("redis://user:password@localhost:6379/1dial_timeout=1")
		options, err := redis.ParseURL("redis://127.0.0.1:6379")
		if err != nil {
			return &pb.GetVerifyCodeReply{
				Code:    1,
				Message: "验证码调用失败(redis配置解析错误)" + err.Error(),
			}, nil
		}
		rdb := redis.NewClient(options)
		defer func() {
			_ = rdb.Close()
		}()
		// ping 测试链接
		rdbStatus, _ := rdb.Ping().Result()
		fmt.Println("ping redis result:", rdbStatus)

		const lift = 60
		status := rdb.Set("CVC:"+req.Telephone, code.Code, lift*time.Second)

		if _, err := status.Result(); err != nil {
			return &pb.GetVerifyCodeReply{
				Code:    1,
				Message: "验证码调用失败(redis操作set失败)",
			}, nil
		}*/
	return &pb.GetVerifyCodeReply{
		Code:           0,
		Message:        "success",
		VerifyCode:     code.Code,
		VerifyCodeTime: int32(time.Now().Unix()),
		VerifyCodeLift: lift,
	}, nil
}
